"use strict";

module.exports = {
  up: async (queryInterface, Sequelize) => {
    // 1) 清理重复的 wallet_address：对于每个重复的地址，保留最小 id 的那条，其他的置为 NULL
    const dialect = queryInterface.sequelize.getDialect();
    if (dialect === "mysql" || dialect === "mariadb") {
      const duplicatesSql = `
        SELECT wallet_address, GROUP_CONCAT(id) as ids, MIN(id) as keep_id
        FROM users
        WHERE wallet_address IS NOT NULL
        GROUP BY wallet_address
        HAVING COUNT(*) > 1
      `;
      const [rows] = await queryInterface.sequelize.query(duplicatesSql);
      for (const row of rows) {
        const ids = String(row.ids)
          .split(",")
          .map((id) => parseInt(id, 10));
        const keepId = parseInt(row.keep_id, 10);
        const idsToNull = ids.filter((id) => id !== keepId);
        if (idsToNull.length > 0) {
          await queryInterface.bulkUpdate(
            "users",
            { wallet_address: null },
            { id: idsToNull }
          );
        }
      }
    } else {
      // 对于其它 dialect，尝试一个通用的方式：使用 CTE（部分 DB 支持）或跳过清理
      // 在多数开发环境中使用 MySQL，因此这里优先考虑 MySQL。若非 MySQL，请在运行迁移前手动清理重复数据。
      console.warn(
        "Non-MySQL dialect detected. Please ensure there are no duplicate wallet_address values before running this migration."
      );
    }

    // 2) 添加唯一索引
    await queryInterface.addIndex("users", ["wallet_address"], {
      unique: true,
      name: "users_wallet_address_unique",
    });
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.removeIndex("users", "users_wallet_address_unique");
  },
};
